import Mock from 'mockjs'

// Generate random data
const rpaAppList = Array.from({ length: 20 }, (_, index) => ({
  id: Mock.Random.guid(),
  name: `RPA应用 ${index + 1}`,
  description: Mock.Random.sentence(5, 10),
  type: Mock.Random.pick(['Web自动化', '桌面自动化', 'API自动化', '数据处理']),
  status: Mock.Random.pick(['运行中', '已停止', '异常']),
  createdAt: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
  updatedAt: Mock.Random.date('yyyy-MM-dd HH:mm:ss')
}))

const rpaTaskList = Array.from({ length: 20 }, (_, index) => ({
  id: Mock.Random.guid(),
  appId: rpaAppList[Mock.Random.integer(0, rpaAppList.length - 1)].id,
  name: `任务 ${index + 1}`,
  status: Mock.Random.pick(['已完成', '执行中', '计划中', '已失败']),
  progress: Mock.Random.integer(0, 100),
  startTime: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
  endTime: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
  robotId: Mock.Random.guid()
}))

const rpaRobotList = Array.from({ length: 15 }, (_, index) => ({
  id: Mock.Random.guid(),
  name: `机器人 ${index + 1}`,
  ip: Mock.Random.ip(),
  status: Mock.Random.pick(['在线', '离线', '维护中']),
  version: `v${Mock.Random.float(1, 5, 1, 2)}`,
  lastActiveTime: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
  systemInfo: {
    cpu: `${Mock.Random.integer(0, 100)}%`,
    memory: `${Mock.Random.integer(0, 100)}%`,
    disk: `${Mock.Random.integer(0, 100)}%`
  }
}))

// BRAC 权限模型
// 定义角色
const roles = [
  {
    id: 'admin',
    name: '管理员',
    description: '系统管理员，拥有所有权限',
    permissions: ['*'], // 通配符表示拥有所有权限
  },
  {
    id: 'manager',
    name: '经理',
    description: '部门经理，负责监督和管理',
    permissions: [
      'app:view', 'app:create', 'app:edit', 'app:delete',
      'task:view', 'task:create', 'task:edit', 'task:delete', 'task:execute', 'task:stop',
      'robot:view', 'robot:connect'
    ],
  },
  {
    id: 'operator',
    name: '操作员',
    description: '系统操作员，负责日常操作',
    permissions: [
      'app:view',
      'task:view', 'task:create', 'task:execute', 'task:stop',
      'robot:view', 'robot:connect'
    ],
  },
  {
    id: 'viewer',
    name: '查看者',
    description: '只读用户，只能查看数据',
    permissions: [
      'app:view',
      'task:view',
      'robot:view'
    ],
  }
]

// 资源类型与权限映射
const resourcePermissions = {
  'app': ['view', 'create', 'edit', 'delete'],
  'task': ['view', 'create', 'edit', 'delete', 'execute', 'stop'],
  'robot': ['view', 'create', 'edit', 'delete', 'connect', 'restart'],
}

// 用户-角色映射
const userRoles = [
  {
    userId: 1, // admin用户ID
    roleIds: ['admin']
  },
  {
    userId: 2,
    roleIds: ['manager']
  },
  {
    userId: 3,
    roleIds: ['operator']
  },
  {
    userId: 4,
    roleIds: ['viewer']
  },
  {
    userId: 5,
    roleIds: ['operator']
  },
  {
    userId: 6,
    roleIds: ['operator']
  },
  {
    userId: 7,
    roleIds: ['viewer']
  },
  {
    userId: 8,
    roleIds: ['manager']
  },
  {
    userId: 9,
    roleIds: ['operator']
  },
  {
    userId: 10,
    roleIds: ['operator']
  },
  {
    userId: 11,
    roleIds: ['operator']
  },
  {
    userId: 12,
    roleIds: ['manager']
  },
  {
    userId: 13,
    roleIds: ['viewer']
  },
  {
    userId: 14,
    roleIds: ['viewer']
  }
]

// 添加角色选择用户
const users = [
  {
    id: 1,
    username: 'admin',
    password: 'admin123',
    email: 'admin@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'admin'
  },
  {
    id: 2,
    username: 'manager',
    password: 'manager123',
    email: 'manager@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'manager'
  },
  {
    id: 3,
    username: 'operator',
    password: 'operator123',
    email: 'operator@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 4,
    username: 'viewer',
    password: 'viewer123',
    email: 'viewer@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'viewer'
  },
  {
    id: 5,
    username: 'developer1',
    password: 'dev123',
    email: 'developer1@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 6,
    username: 'tester1',
    password: 'test123',
    email: 'tester1@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 7,
    username: 'analyst1',
    password: 'analyst123',
    email: 'analyst1@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'viewer'
  },
  {
    id: 8,
    username: 'manager2',
    password: 'manager123',
    email: 'manager2@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'manager'
  },
  {
    id: 9,
    username: 'developer2',
    password: 'dev123',
    email: 'developer2@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 10,
    username: 'tester2',
    password: 'test123',
    email: 'tester2@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 11,
    username: 'developer3',
    password: 'dev123',
    email: 'developer3@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'operator'
  },
  {
    id: 12,
    username: 'director1',
    password: 'director123',
    email: 'director1@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'manager'
  },
  {
    id: 13,
    username: 'guest1',
    password: 'guest123',
    email: 'guest1@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'viewer'
  },
  {
    id: 14,
    username: 'guest2',
    password: 'guest123',
    email: 'guest2@example.com',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    role: 'viewer'
  }
]

// Mock APIs
Mock.setup({
  timeout: '200-600'
})

// RPA 应用管理
Mock.mock('/api/rpa/apps', 'get', () => ({
  code: 200,
  message: 'success',
  data: rpaAppList
}))

Mock.mock('/api/rpa/apps/view', 'post', (options) => {
  const { id } = JSON.parse(options.body)
  const app = rpaAppList.find(app => app.id === id)
  return {
    code: 200,
    message: '获取应用详情成功',
    data: {
      ...app,
      detailedInfo: {
        creator: '管理员',
        version: Mock.Random.increment(1.0).toFixed(1),
        lastModified: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
        configuration: {
          maxThreads: Mock.Random.integer(1, 8),
          timeout: `${Mock.Random.integer(10, 60)}分钟`,
          autoRetry: Mock.Random.boolean(),
          notifyOnCompletion: Mock.Random.boolean()
        },
        compatibleRobots: ['通用机器人', 'OCR机器人', 'Web自动化机器人'].slice(0, Mock.Random.integer(1, 3)),
        dependencies: ['数据抓取模块', 'PDF解析插件', 'Excel处理模块'].slice(0, Mock.Random.integer(1, 3))
      }
    }
  }
})

// 修改 Mock 数据的日期格式
Mock.Random.extend({
  datetime: function() {
    let date = new Date()
    let year = date.getFullYear()
    let month = String(date.getMonth() + 1).padStart(2, '0')
    let day = String(date.getDate()).padStart(2, '0')
    let hours = String(date.getHours()).padStart(2, '0')
    let minutes = String(date.getMinutes()).padStart(2, '0')
    let seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
})

// RPA 应用管理
Mock.mock('/api/rpa/apps/edit', 'post', (options) => {
  const app = JSON.parse(options.body)
  return {
    code: 200,
    message: '应用编辑成功',
    data: {
      ...app,
      updatedAt: Mock.Random.datetime(),
      changes: ['更新了应用信息']
    }
  }
})

// RPA 运行管理
Mock.mock('/api/rpa/tasks', 'get', () => ({
  code: 200,
  message: 'success',
  data: rpaTaskList
}))

Mock.mock('/api/rpa/tasks/view', 'post', (options) => {
  const { id } = JSON.parse(options.body)
  const task = rpaTaskList.find(task => task.id === id)
  return {
    code: 200,
    message: '获取任务详情成功',
    data: {
      ...task,
      detailedInfo: {
        creator: '管理员',
        executionLogs: [
          '任务已创建',
          '任务已排入队列',
          '任务开始执行',
          ...Array.from({ length: Mock.Random.integer(1, 3) }, () => Mock.Random.sentence(3, 6))
        ],
        parameters: {
          target: Mock.Random.pick(['invoice-process', 'data-collection', 'web-automation']),
          priority: Mock.Random.pick(['高', '中', '低']),
          retry: Mock.Random.integer(0, 3)
        },
        relatedRobots: rpaRobotList.slice(0, Mock.Random.integer(1, 3)).map(robot => robot.name),
        nextExecutionTime: task.status === '计划中' ? Mock.Random.date('yyyy-MM-dd HH:mm:ss') : '无'
      }
    }
  }
})

// RPA 运行管理
Mock.mock('/api/rpa/tasks/edit', 'post', (options) => {
  const task = JSON.parse(options.body)
  return {
    code: 200,
    message: '任务编辑成功',
    data: {
      ...task,
      updatedAt: Mock.Random.datetime()
    }
  }
})

Mock.mock('/api/rpa/tasks/stop', 'post', (options) => {
  const { id, name } = JSON.parse(options.body)
  return {
    code: 200,
    message: '停止任务命令已发送',
    data: {
      taskName: name,
      status: '已停止',
      stopTime: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
      reason: '用户手动停止',
      savedProgress: Mock.Random.integer(0, 100)
    }
  }
})

// RPA 机器人管理
Mock.mock('/api/rpa/robots', 'get', () => ({
  code: 200,
  message: 'success',
  data: rpaRobotList
}))

Mock.mock('/api/rpa/robots/view', 'post', (options) => {
  const { id } = JSON.parse(options.body)
  const robot = rpaRobotList.find(robot => robot.id === id)
  return {
    code: 200,
    message: '获取机器人详情成功',
    data: {
      ...robot,
      detailedInfo: {
        creator: '管理员',
        createdAt: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
        runningTasks: Mock.Random.integer(0, 5),
        totalExecutions: Mock.Random.integer(100, 1000),
        successRate: `${Mock.Random.float(80, 100, 1, 2)}%`,
        capabilities: ['Web自动化', 'OCR识别', '数据处理'].slice(0, Mock.Random.integer(1, 3)),
        configuration: {
          maxConcurrentTasks: Mock.Random.integer(1, 5),
          autoUpdate: Mock.Random.boolean(),
          logLevel: Mock.Random.pick(['DEBUG', 'INFO', 'WARN', 'ERROR'])
        }
      }
    }
  }
})

// RPA 机器人管理
Mock.mock('/api/rpa/robots/edit', 'post', (options) => {
  const robot = JSON.parse(options.body)
  return {
    code: 200,
    message: '机器人编辑成功',
    data: {
      ...robot,
      updatedAt: Mock.Random.datetime()
    }
  }
})

Mock.mock('/api/rpa/robots/connect', 'post', (options) => {
  const { id, name } = JSON.parse(options.body)
  return {
    code: 200,
    message: '连接机器人成功',
    data: {
      robotName: name,
      status: '在线',
      connectionTime: Mock.Random.date('yyyy-MM-dd HH:mm:ss'),
      sessionId: Mock.Random.guid()
    }
  }
})

// RPA 机器人管理
Mock.mock('/api/rpa/robots/restart', 'post', (options) => {
  const { id, name } = JSON.parse(options.body)
  return {
    code: 200,
    message: '重启命令已发送',
    data: {
      robotName: name,
      status: '维护中',
      restartTime: Mock.Random.datetime(),
      estimatedCompletionTime: Mock.Random.datetime()
    }
  }
})

// 权限相关API
Mock.mock('/api/auth/roles', 'get', () => ({
  code: 200,
  message: 'success',
  data: roles
}))

Mock.mock('/api/auth/users/roles', 'post', (options) => {
  const { userId } = JSON.parse(options.body)
  const userRole = userRoles.find(ur => ur.userId === userId)
  
  if (!userRole) {
    return {
      code: 404,
      message: '未找到用户角色信息',
      data: null
    }
  }
  
  const userRoleDetails = userRole.roleIds.map(roleId => {
    return roles.find(role => role.id === roleId)
  }).filter(Boolean)
  
  return {
    code: 200,
    message: 'success',
    data: userRoleDetails
  }
})

Mock.mock('/api/auth/users', 'get', () => ({
  code: 200,
  message: 'success',
  data: users
}))

Mock.mock('/api/auth/permissions/check', 'post', (options) => {
  const { userId, permission } = JSON.parse(options.body)
  const userRole = userRoles.find(ur => ur.userId === userId)
  
  if (!userRole) {
    return {
      code: 403,
      message: '无权访问',
      data: { hasPermission: false }
    }
  }
  
  // 获取用户所有角色的权限
  const userPermissions = []
  userRole.roleIds.forEach(roleId => {
    const role = roles.find(r => r.id === roleId)
    if (role) {
      userPermissions.push(...role.permissions)
    }
  })
  
  // 检查是否有通配符权限或特定权限
  const hasPermission = userPermissions.includes('*') || userPermissions.includes(permission)
  
  return {
    code: 200,
    message: 'success',
    data: { hasPermission }
  }
})

export default Mock 